import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // progress bar style

Vue.use(VueRouter)

import Layout from '@/layout'
import EmptyLayout from '@/layout/empty'

const constantRoutes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/502',
        name: '502',
        component: () => import('@/views/502'),
        meta: {
            title: '502'
        }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('@/views/sales_management/dashboard/index'),
                meta: {
                    title: store.state.settings.dashboardTitle
                }
            },
            {
                path: 'personal',
                component: EmptyLayout,
                redirect: '/personal/setting',
                meta: {
                    title: '个人中心',
                    breadcrumb: false
                },
                children: [
                    {
                        path: 'setting',
                        name: 'personalSetting',
                        component: () => import('@/views/personal/setting'),
                        meta: {
                            title: '个人设置'
                        }
                    },
                    {
                        path: 'edit/password',
                        name: 'personalEditPassword',
                        component: () => import('@/views/personal/edit.password'),
                        meta: {
                            title: '修改密码'
                        }
                    }
                ]
            },
            {
                path: 'reload',
                name: 'reload',
                component: () => import('@/views/reload')
            }
        ]
    }
]

// 当 children 不为空的主导航只有一项时，则隐藏
let asyncRoutes = [
    // 广告投放
    {
        meta: {
            title: '广告投放',
            icon: 'sidebar-ad'
        },
        children: [
            // 巨量引擎
            // {
            //     path: '/junliang',
            //     component: Layout,
            //     name: 'Junliang',
            //     meta: {
            //         title: '巨量引擎',
            //         icon: 'juliangyinqing',
            //         breadcrumb: false
            //     },
            //     children: [
            //         {
            //             path: '/juliang/invest',
            //             name: 'JuliangInvest',
            //             component: () => import('@/views/advertisement/juliang/invest'),
            //             meta: {
            //                 title: '投放管理'
            //             }
            //         },
            //         {
            //             path: '/juliang/account',
            //             name: 'JUliangAccount',
            //             component: () => import('@/views/advertisement/juliang/account'),
            //             meta: {
            //                 title: '账户信息'
            //             }
            //         }
            //     ]
            // },
            // 百度营销
            {
                path: '/baidu',
                component: Layout,
                name: 'Baidu',
                meta: {
                    title: '百度营销',
                    icon: 'baiduyingxiao',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/baidu/account',
                        name: 'BaiduAccount',
                        component: () => import('@/views/advertisement/baidu/account'),
                        meta: {
                            title: '账户信息'
                        }
                    },
                    {
                        path: '/baidu/invest',
                        name: 'BaiduInvest',
                        component: () => import('@/views/advertisement/baidu/invest'),
                        meta: {
                            title: '投放管理',
                            sidebar: false,
                            activeMenu: '/order'
                        }
                    }
                ]
            }
        ]
    },
    // 销售管理
    {
        meta: {
            title: '销售管理',
            icon: 'sidebar-videos'
        },
        children: [
            // 工作台
            {
                path: '/dashboard',
                component: Layout,
                name: 'dashBoard',
                redirect: '/dashboard/index',
                meta: {
                    title: '工作台',
                    icon: 'liuliang',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/dashboard/index',
                        name: 'dashboardIndex',
                        component: () => import('@/views/sales_management/dashboard/index'),
                        meta: {
                            title: '工作台',
                            sidebar: false,
                            breadcrumb: true,
                            activeMenu: '/dashboard'
                        }
                    }
                ]
            },
            // 线索管理
            {
                path: '/clue',
                component: Layout,
                name: 'clueManagement',
                meta: {
                    title: '线索管理',
                    icon: 'fabu',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/clue/mine',
                        name: 'myClue',
                        component: () => import('@/views/sales_management/clue/mine'),
                        meta: {
                            title: '我的线索'
                        }
                    },
                    {
                        path: '/clue/public',
                        name: 'publicClue',
                        component: () => import('@/views/sales_management/clue/public'),
                        meta: {
                            title: '公共线索'
                        }
                    }
                ]
            },
            // 客户管理
            {
                path: '/custom',
                component: Layout,
                name: 'customManagement',
                meta: {
                    title: '客户管理',
                    icon: 'kehu',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/custom/mine',
                        name: 'mCustom',
                        component: () => import('@/views/sales_management/custom/mine'),
                        meta: {
                            title: '我的客户'
                        }
                    },
                    {
                        path: '/custom/public',
                        name: 'publicCustom',
                        component: () => import('@/views/sales_management/custom/public'),
                        meta: {
                            title: '公共客户'
                        }
                    }
                ]
            },
            // 签约管理
            {
                path: '/niche',
                component: Layout,
                name: 'niche',
                redirect: '/niche/index',
                meta: {
                    title: '签约管理',
                    icon: 'danmaijia',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/niche/index',
                        name: 'nicheIndex',
                        component: () => import('@/views/sales_management/niche/index'),
                        meta: {
                            title: '签约管理',
                            sidebar: false,
                            activeMenu: '/niche'
                        }
                    }
                ]
            },
            // 预约管理
            {
                path: '/reservation',
                component: Layout,
                name: 'reservation',
                redirect: '/reservation/index',
                meta: {
                    title: '预约管理',
                    icon: 'fahuoshijian',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/reservation/index',
                        name: 'reservationIndex',
                        component: () => import('@/views/sales_management/reservation/index'),
                        meta: {
                            title: '预约管理',
                            sidebar: false,
                            activeMenu: '/reservation'
                        }
                    }
                ]
            },
            // 回款管理
            {
                path: '/order',
                component: Layout,
                name: 'order',
                redirect: '/order/index',
                meta: {
                    title: '回款管理',
                    icon: 'dingdan',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/order/index',
                        name: 'orderIndex',
                        component: () => import('@/views/sales_management/order/index'),
                        meta: {
                            title: '回款管理',
                            sidebar: false,
                            activeMenu: '/order'
                        }
                    }
                ]
            },
            // 分配记录
            {
                path: '/allocationRecord',
                component: Layout,
                name: 'AllocationRecord',
                redirect: '/allocationRecord/index',
                meta: {
                    title: '分配记录',
                    icon: 'fenpei',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/allocationRecord/index',
                        name: 'AllocationRecordIndex',
                        component: () => import('@/views/sales_management/allocationRecord/index'),
                        meta: {
                            title: '分配记录',
                            sidebar: false,
                            activeMenu: '/allocationRecord'
                        }
                    }
                ]
            },
            // 账户消费情况
            {
                path: '/accountInfo',
                component: Layout,
                name: 'AccountInfo',
                redirect: '/accountInfo/index',
                meta: {
                    title: '账户消费情况',
                    icon: 'shuju1',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/accountInfo/index',
                        name: 'AccountInfoIndex',
                        component: () => import('@/views/sales_management/accountInfo/index'),
                        meta: {
                            title: '账户消费情况',
                            sidebar: false,
                            activeMenu: '/accountInfo'
                        }
                    }
                ]
            },
            // 全局搜索
            {
                path: '/search',
                component: Layout,
                name: 'Search',
                redirect: '/search/index',
                meta: {
                    title: '分配记录',
                    icon: 'fenpei',
                    breadcrumb: false,
                    sidebar: false
                },
                children: [
                    {
                        path: '/search/index',
                        name: 'SearchIndex',
                        component: () => import('@/views/sales_management/search/index'),
                        meta: {
                            title: '预约管理',
                            sidebar: false
                        }
                    }
                ]
            }
        ]
    },
    // 决策分析
    {
        meta: {
            title: '决策分析',
            icon: 'sidebar-ecology'
        },
        children: [
            // 客户资产分析
            {
                path: '/clientAssets',
                component: Layout,
                name: 'clientAssets',
                meta: {
                    title: '客户资产分析',
                    icon: 'cankaojia',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/clientAssets/clueAssets',
                        name: 'ClueAssets',
                        component: () => import('@/views/decision_analysis/clientAssets/clueAssets'),
                        meta: {
                            title: '线索资产分析'
                        }
                    },
                    {
                        path: '/clientAssets/customerAssets',
                        name: 'CustomerAssets',
                        component: () => import('@/views/decision_analysis/clientAssets/customerAssets'),
                        meta: {
                            title: '客户资产分析'
                        }
                    },
                    {
                        path: '/salesProcess/member',
                        name: 'member',
                        component: () => import('@/views/decision_analysis/salesProcess/member'),
                        meta: {
                            title: '销售跟进分析'
                        }
                    },
                    {
                        path: '/clientAssets/businessOpportunityDeal',
                        name: 'BusinessOpportunityDeal',
                        component: () => import('@/views/decision_analysis/clientAssets/businessOpportunityDeal'),
                        meta: {
                            title: '商机资产分析'
                        }
                    }
                ]
            },
            // 销售过程分析
            {
                path: '/salesProcess',
                component: Layout,
                name: '销售过程分析',
                meta: {
                    title: '销售过程分析',
                    icon: 'shuju1',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/salesProcess/salesDevelop',
                        name: 'SalesDevelop',
                        component: () => import('@/views/decision_analysis/salesProcess/salesDevelop'),
                        meta: {
                            title: '线索分配分析'
                        }
                    },
                    // {
                    //     path: '/salesProcess/staffPerformance',
                    //     name: 'StaffPerformance',
                    //     component: () => import('@/views/decision_analysis/salesProcess/staffPerformance'),
                    //     meta: {
                    //         title: '销售电话分析'
                    //     }
                    // },
                    {
                        path: 'assign',
                        name: 'Assign',
                        component: () => import('@/views/decision_analysis/salesProcess/assign'),
                        meta: {
                            title: '客户分配分析'
                        }
                    },
                    {
                        path: '/salesProcess/reservation',
                        name: 'Reservation',
                        component: () => import('@/views/decision_analysis/salesProcess/reservation'),
                        meta: {
                            title: '预约客户分析'
                        }
                    }
                ]
            },
            // 销售转化分析
            {
                path: '/salesConversion',
                component: Layout,
                name: '销售转化分析',
                meta: {
                    title: '销售转化分析',
                    icon: 'shangxiajia',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/salesConversion/salesConversion',
                        name: 'SalesConversion',
                        component: () => import('@/views/decision_analysis/salesConversion/salesConversion'),
                        meta: {
                            title: '销售转化分析'
                        }
                    },
                    {
                        path: '/salesConversion/clueTransform',
                        name: 'ClueTransform',
                        component: () => import('@/views/decision_analysis/salesConversion/clueTransform'),
                        meta: {
                            title: '线索转化分析'
                        }
                    },
                    {
                        path: '/salesConversion/customerTransform',
                        name: 'CustomerTransform',
                        component: () => import('@/views/decision_analysis/salesConversion/customerTransform'),
                        meta: {
                            title: '客户转化分析'
                        }
                    },
                    {
                        path: '/salesConversion/opportunityTransform',
                        name: 'OpportunityTransform',
                        component: () => import('@/views/decision_analysis/salesConversion/opportunityTransform'),
                        meta: {
                            title: '商机转化分析'
                        }
                    }
                ]
            },
            // 销售结果分析
            {
                path: '/salesResult',
                component: Layout,
                name: '销售结果分析',
                meta: {
                    title: '销售结果分析',
                    icon: 'fenxi',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/salesResult/orderTypeAnalysis',
                        name: 'OrderTypeAnalysis',
                        component: () => import('@/views/decision_analysis/salesResult/orderTypeAnalysis'),
                        meta: {
                            title: '订单收款分析'
                        }
                    },
                    {
                        path: '/salesResult/order',
                        name: 'Order',
                        component: () => import('@/views/decision_analysis/salesResult/order'),
                        meta: {
                            title: '订单年度分析'
                        }
                    },
                    {
                        path: '/salesResult/transactionCustomersAnalysis',
                        name: 'TransactionCustomersAnalysis',
                        component: () => import('@/views/decision_analysis/salesResult/transactionCustomersAnalysis'),
                        meta: {
                            title: '签单客户分析'
                        }
                    }
                ]
            },
            // 市场推广分析
            {
                path: '/marketPromotion',
                component: Layout,
                name: '市场推广分析',
                meta: {
                    title: '市场推广分析',
                    icon: 'dianpu',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/marketPromotion/channelTransform',
                        name: 'ChannelTransform',
                        component: () => import('@/views/decision_analysis/marketPromotion/channelTransform'),
                        meta: {
                            title: '渠道转化分析'
                        }
                    },
                    {
                        path: '/marketPromotion/cuevalidity',
                        name: 'Cuevalidity',
                        component: () => import('@/views/decision_analysis/marketPromotion/cuevalidity'),
                        meta: {
                            title: '渠道质量分析'
                        }
                    }
                ]
            }
        ]
    },
    // 系统配置
    {
        meta: {
            title: '系统配置',
            icon: 'sidebar-setting'
        },
        children: [
            // 配置管理
            {
                path: '/config',
                component: Layout,
                name: 'configManagement',
                meta: {
                    title: '配置管理',
                    icon: 'peizhi',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/config/cluePool',
                        name: 'CluePool',
                        component: () => import('@/views/system_management/clueConfig/index'),
                        meta: {
                            title: '线索池配置'
                        }
                    },
                    {
                        path: '/config/merchantPool',
                        name: 'MerchantPool',
                        component: () => import('@/views/system_management/merchantConfig/index'),
                        meta: {
                            title: '分配商户配置'
                        }
                    },
                    {
                        path: '/config/clueRuleConfig',
                        name: 'ClueRuleConfig',
                        component: () => import('@/views/system_management/clueRuleConfig/index'),
                        meta: {
                            title: '线索规则配置'
                        }
                    },
                    {
                        path: '/config/customRuleConfig',
                        name: 'CustomRule',
                        component: () => import('@/views/system_management/customRuleConfig/index'),
                        meta: {
                            title: '客户规则配置'
                        }
                    },
                    {
                        path: '/config/holidayConfig',
                        name: 'holidayConfig',
                        component: () => import('@/views/system_management/holidayConfig/index'),
                        meta: {
                            title: '请假管理'
                        }
                    }
                ]
            },
            // 系统管理
            {
                path: '/system',
                component: Layout,
                name: 'systemManagement',
                meta: {
                    title: '系统管理',
                    icon: 'shezhi',
                    breadcrumb: false
                },
                children: [
                    {
                        path: '/system/user',
                        name: 'userManagement',
                        component: () => import('@/views/system_management/user/index'),
                        meta: {
                            title: '用户管理'
                        }
                    },
                    {
                        path: '/system/department',
                        name: 'departManagement',
                        component: () => import('@/views/system_management/department/index'),
                        meta: {
                            title: '部门管理'
                        }
                    },
                    {
                        path: '/system/role',
                        name: 'roleManagement',
                        component: () => import('@/views/system_management/role/index'),
                        meta: {
                            title: '角色管理'
                        }
                    }
                ]
            }
        ]
    }
]

const lastRoute = [{
    path: '*',
    component: () => import('@/views/404'),
    meta: {
        title: '404',
        sidebar: false
    }
}]

const router = new VueRouter({
    routes: constantRoutes
})

// 解决路由在 push/replace 了相同地址报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}

router.beforeEach(async(to, from, next) => {
    store.state.settings.enableProgress && NProgress.start()
    // 已经登录，但还没根据权限动态挂载路由
    if (store.getters['user/isLogin'] && !store.state.menu.isGenerate) {
        router.matcher = new VueRouter({
            routes: constantRoutes
        }).matcher
        const accessRoutes = await store.dispatch('menu/generateRoutes', {
            asyncRoutes,
            currentPath: to.path
        })
        accessRoutes.push(...lastRoute)
        accessRoutes.forEach(route => {
            router.addRoute(route)
        })
        next({ ...to, replace: true })
    }
    if (store.state.menu.isGenerate) {
        store.commit('menu/setHeaderActived', to.path)
    }
    to.meta.title && store.commit('settings/setTitle', to.meta.title)
    // debugger
    if (store.getters['user/isLogin']) {
        if (to.name) {
            if (to.matched.length !== 0) {
                // 如果已登录状态下，进入登录页会强制跳转到控制台页面
                if (to.name == 'login') {
                    next({
                        name: 'dashboard',
                        replace: true
                    })
                } else if (!store.state.settings.enableDashboard && to.name == 'dashboard') {
                    // 如果未开启控制台页面，则默认进入侧边栏导航第一个模块，但如果侧边栏导航没有模块，则还是进入控制台页面
                    if (store.getters['menu/sidebarRoutes'].length > 0) {
                        next({
                            name: store.getters['menu/sidebarRoutes'][0].name,
                            replace: true
                        })
                    }
                }
            } else {
                // 如果是通过 name 跳转，并且 name 对应的路由没有权限时，需要做这步处理，手动指向到 404 页面
                next({
                    path: '/404'
                })
            }
        }
    } else {
        if (to.name != 'login') {
            next({
                name: 'login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    }
    next()
})

router.afterEach(() => {
    store.state.settings.enableProgress && NProgress.done()
})

export default router
